package com.start.autumn.config;

import com.alibaba.cloud.sentinel.SentinelProperties;
import com.alibaba.cloud.sentinel.custom.SentinelBeanPostProcessor;
import com.alibaba.cloud.sentinel.custom.SentinelDataSourceHandler;
import com.alibaba.csp.sentinel.annotation.aspectj.SentinelResourceAspect;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;

@Configuration(proxyBeanMethods = false)
@ConditionalOnProperty(name = {"spring.cloud.sentinel.enabled"}, matchIfMissing = true)
@EnableConfigurationProperties({SentinelProperties.class,SentinelCustomProperties.class})
public class SentinelAutoConfiguration {

    @Bean
    @ConditionalOnMissingBean
    public SentinelResourceAspect sentinelResourceAspect() {
        return new SentinelResourceAspect();
    }
    @Bean
    @ConditionalOnMissingBean
    @ConditionalOnClass(name = {"org.springframework.web.client.RestTemplate"})
    @ConditionalOnProperty(name = {"resttemplate.sentinel.enabled"}, havingValue = "true", matchIfMissing = true)
    public SentinelBeanPostProcessor sentinelBeanPostProcessor(ApplicationContext applicationContext) {
        return new SentinelBeanPostProcessor(applicationContext);
    }

    @Bean
    @ConditionalOnMissingBean
    public SentinelDataSourceHandler sentinelDataSourceHandler(DefaultListableBeanFactory beanFactory, SentinelProperties sentinelProperties, Environment env) {
        return new SentinelDataSourceHandler(beanFactory, sentinelProperties, env);
    }
}
